/*    file: RtpPackager.cpp
 *    desc:
 * 
 * created: 2014-07-21 15:24:43
 *  author: zhengchuanjiang
 * company: 
 */

#include "stdafx.h"
#include "RtpPackager.h"
#include "RtpHeader.h"
#include "comn\TStringUtil.h"

RtpPackager::RtpPackager():
    m_file(),
    m_tsOffset(),
    m_seqOffset(),
    m_count(),
    m_lastTs()
{
}

RtpPackager::~RtpPackager()
{
    close();
}

bool RtpPackager::open(const char* filename)
{
    fopen_s(&m_file, filename, "wb");
    return (m_file != NULL);
}

bool RtpPackager::isOpen()
{
    return (m_file != NULL);
}

void RtpPackager::close()
{
    if (m_file)
    {
        fclose(m_file);
        m_file = NULL;
    }
}


static unsigned char s_startCode[] = { 0, 0, 0, 1};


bool hasDahua(BYTE* ptr, UINT16 size)
{
    int fcc = MAKEFOURCC('D', 'H', 'A', 'V');
    int code = *(int*)ptr;
    return code == fcc;
}

void RtpPackager::write(BYTE* ptr, UINT16 size)
{
    if (!isOpen())
    {
        return;
    }

    RTP_FIXED_HEADER* rtpHeader = (RTP_FIXED_HEADER*)ptr;
    unsigned long timestamp = ntohl(rtpHeader->timestamp);
    unsigned short seq = ntohs(rtpHeader->seq_no);

    if (m_count == 0)
    {
        m_tsOffset = timestamp;
        m_seqOffset = seq;
        m_lastTs = timestamp;
    }

    m_count ++;

    unsigned long delta = timestamp - m_lastTs;
    m_lastTs = timestamp;

	BYTE* p = ptr + sizeof(RTP_FIXED_HEADER);
	int dataSize = size - sizeof(RTP_FIXED_HEADER);
	if (dataSize > 8) {
		dataSize = 8;
	}

	std::string str = comn::StringCast::toHexString(p, dataSize);

    fprintf(m_file, "seq:%d, ts:%u, ts delta:%5lu, marker:%d, size:%4d, data:%s\n",
        seq,
        timestamp,
        delta,
        rtpHeader->marker,
        size,
		str.c_str()
        );

}
